from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from dotenv import load_dotenv
import os
from backend.api import alerts, clients, websocket,auth
from backend.db.database import engine
from backend.db.models import Base
from backend.core.scheduler import start_scheduler
from backend.core.heartbeat import check_client_online_status

# 加载环境变量
load_dotenv()

# 创建数据库表（首次启动时执行）
Base.metadata.create_all(bind=engine)

# 初始化FastAPI应用
app = FastAPI(title="GuGuAlert Server", version="1.0")

# 解决跨域问题（允许前端和客户端访问）
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173","http://localhost:3000/"],  # 生产环境需替换为具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(alerts.router)
app.include_router(clients.router)  # 客户端状态API（类似alerts.py实现）
app.include_router(websocket.router)

app.include_router(auth.router)

# 启动时初始化定时任务
@app.on_event("startup")
async def startup_event():
    start_scheduler()  # 启动提醒定时任务
    # 启动客户端心跳检查（每10秒一次）
    from apscheduler.schedulers.asyncio import AsyncIOScheduler
    heartbeat_scheduler = AsyncIOScheduler(timezone="UTC")
    heartbeat_scheduler.add_job(
        check_client_online_status,
        trigger="interval",
        seconds=10,
        id="client_heartbeat_check"
    )
    heartbeat_scheduler.start()
    print("服务器启动成功，API文档：http://localhost:8000/docs")

# 根路由（测试用）
@app.get("/")
def read_root():
    return {"message": "GuGuAlert Server is running"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host=os.getenv("API_HOST"),
        port=int(os.getenv("API_PORT")),
        reload=True  # 开发环境启用热重载
    )